package JAVA300.第十一章多线程;

import java.util.ArrayList;
import java.util.List;

/**
 * 实例练习同步问题1
 * 电影院抢票--考虑位置分布
 * 将座位数量int改为容器
 */
public class thread_16_synchronized_exp1_1 {
    public static void main(String[] args) {
        List<Integer> available = new ArrayList<>();
        available.add(1);
        available.add(2);
        available.add(3);
        available.add(4);
        available.add(5);
        available.add(6);

        List<Integer> hqqWants = new ArrayList<>();
        hqqWants.add(1);
        hqqWants.add(2);
        hqqWants.add(3);

        List<Integer> qyhWants = new ArrayList<>();
        qyhWants.add(1);
        qyhWants.add(6);




        Ciname1 ciname = new Ciname1(available,"CGV");
        new Thread(new Customs1(ciname,hqqWants),"hqq").start();
        new Thread(new Customs1(ciname,qyhWants),"qyh").start();

    }
}

class Ciname1 {
    List<Integer> available;//可选座位列表
    String name ;//影院

    public Ciname1(List<Integer> available, String name) {
        this.available = available;
        this.name = name;
    }

    public boolean bookTickets(List<Integer> wantSeats){

        System.out.println("可选座位数目："+available);

        //判断座位是否已经被选
        //将原有的和所需的相减 之后做对比
        List<Integer> copy = new ArrayList<>();
        copy.addAll(available);//拷贝一份做计算 避免购票失败影响原有数量


        copy.removeAll(wantSeats);
        //判断大小--原来的减去剔除过的copy  如果数量与wants一致 说明均剔除成功 也就是座位满足
        if (available.size()-copy.size() != wantSeats.size()) {

            return false;

        }else {
            available = copy;//购票成功 将卖完之后新的座位覆盖
            return true;
        }
    }
}

class Customs1 implements Runnable{

    Ciname1 ciname;
    List<Integer> seats;

    public Customs1(Ciname1 ciname, List<Integer> tickets) {
        this.ciname = ciname;
        this.seats = tickets;
    }

    @Override
    public void run() {

        //没加同步 导致可用都成20
        synchronized (ciname){
            boolean flag = ciname.bookTickets(seats);
            if (flag){
                System.out.println("购票成功"+Thread.currentThread().getName()+"-->"+seats);
            }else {
                System.out.println("出票失败"+Thread.currentThread().getName()+"票数不够");
            }

        }


    }
}
